package com.ocom.payhandle.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payhandle.QrCardPayRequest;
import com.ocom.common.request.payhandle.ShoppingCartRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.GzhParamVo;
import com.ocom.common.vo.payconfig.kitchenprinter.PlanKitchenPrinterRequest;
import com.ocom.common.vo.pyhandle.ShoppingCartRecordVo;
import com.ocom.common.vo.pyhandle.UserOrdersQueryVo;
import com.ocom.payhandle.feign.PayConfigClientService;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;


@Slf4j
@RestController
public class ShoppingCartController {

    @Autowired
    DeviceInfoService deviceInfoService;

    @Autowired
    XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    XfPointInfoService xfPointInfoService;

    @Autowired
    XfChannelInfoService xfChannelInfoService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private XfDiscountConfigServcie xfDiscountConfigServcie;

    @Autowired
    private XfUserparamConfigService xfUserparamConfigService;

    @Autowired
    private ConsTypeConfigService consTypeConfigService;

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    XfShoppingCartService xfShoppingCartService;

    @Autowired
    PayFunService payFunService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private XfRecordFeign xfRecordFeign;


    @Autowired
    private XfZoneDateService xfZoneDateService;


    @Autowired
    private XfRecordProcessExxxService xfRecordProcessExxxService;

    //在线购物车消费
    @PostMapping(PayHandleUrl.URL_shoppingCartPay)
    public Result shoppingCartPay(@RequestBody ShoppingCartRequest request) {
//        log.info("【购物车】【{}】【{}】【{}】", request.getTradeNo(), request, "灰度2025年3月5日16:00:53");
        try {

            String tradeNoRedis = "shoppingCartPay:" + request.getCompanyId() + ":" + request.getTradeNo();

            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                log.info("请求方式2CO7AzfN:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getTradeNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            //判断是什么支付类型
            //1-刷卡，4-刷脸，5-付款码，7-ocom离线码 8微信人脸
            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), request.getPId());
            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), request.getPId());

            if (entityXfAccountInfo.getAccountState() != 0) {
                return ResultUtil.error(ResultEnum.Err_4022);
            }

            if (entityPersonnelInfo == null) {
                return ResultUtil.error(ResultEnum.Err_4017);
            }
            if (entityPersonnelInfo.getStatus() != 0) {
                return ResultUtil.error(ResultEnum.Err_4023);
            }

            //筛选过后的菜品
            List<EntityXfShoppingCart> xfShoppingCarts = xfShoppingCartService.getDishesFormCart(request.getCompanyId(), request);

            if (xfShoppingCarts.size() == 0) {
                return ResultUtil.error(ResultEnum.Err_3080);
            }

            xfShoppingCartService.updateDishesFormCart(request.getCompanyId(),request,1);


            //初始订单数据
            EntityXfRecordProcess entityXfRecordProcess = new ShoppingCartRecordVo();
            entityXfRecordProcess.setOpType(12l);//小程序点餐
            entityXfRecordProcess.setComId(request.getCompanyId());
            entityXfRecordProcess.setDeviceNo("00000000");
            entityXfRecordProcess.setDeviceName(request.getGzhAppid());
            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
            entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
            entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
            entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
            entityXfRecordProcess.setAccTypeId(entityXfAccountInfo.getAccTypeId());
            Date date = new Date();
            entityXfRecordProcess.setConsTime(date);
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            entityXfRecordProcess.setConsState(request.getConsState());
            //查询个人所在的组织
            entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
            //查询收费的和商家信息
            EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.getMerchInfo(request.getCompanyId(), request.getMerchId());
            entityXfRecordProcess.setMerchId(request.getMerchId().longValue());
            entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());

            //查询条件初始化
            entityXfRecordProcess.setDiscount(0l);

            if (entityPersonnelInfo.getDeptId() == null) {
                entityPersonnelInfo.setDeptId(0l);
            } else {
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }
            entityXfRecordProcess.setConsType(request.getConsType());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPlatOrderNo(request.getTradeNo());

            if(request.getType()==7){
                entityXfRecordProcess.setOpTypeDiff(100l);
                entityXfRecordProcess.setPayWay(0);
            }
            if(request.getType()==1){
                entityXfRecordProcess.setOpTypeDiff(201l);
                entityXfRecordProcess.setPayWay(1);
            }
            if(request.getType()==2){
                entityXfRecordProcess.setOpTypeDiff(204l);
                entityXfRecordProcess.setPayWay(7);
            }
            if(request.getType()==3 || request.getType()==10){
                entityXfRecordProcess.setOpTypeDiff(201l);
                entityXfRecordProcess.setPayWay(1);
            }
            if(request.getType()==4){
                entityXfRecordProcess.setOpTypeDiff(309l);
                entityXfRecordProcess.setPayWay(30);
            }
            if(request.getType()==5){
                entityXfRecordProcess.setOpTypeDiff(201l);
                entityXfRecordProcess.setPayWay(7);
            }
            if(request.getType()==6){
                entityXfRecordProcess.setOpTypeDiff(201l);
                entityXfRecordProcess.setPayWay(6);
            }

            //查询配置信息向统一平台发起支付
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);
            if (request.getType() != 7) {

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }
                entityXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
            }

            //拼装订单列表！！！！！！！！
            List<ShoppingCartRecordVo> recordVoList = new ArrayList<>();

            List<String> exist = new ArrayList<>();
            Integer inx = 0;

            for (EntityXfShoppingCart entityXfShoppingCart : xfShoppingCarts) {
                String key = entityXfShoppingCart.getMealDate() + "#" + entityXfShoppingCart.getMealNo() + "#" + entityXfShoppingCart.getMealplanId();

                EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
                entityXfGoodsListProcess.setComId(request.getCompanyId());
                entityXfGoodsListProcess.setDeviceNo("00000000");
                entityXfGoodsListProcess.setPointId(entityXfShoppingCart.getPointId());
                entityXfGoodsListProcess.setMerchId(request.getMerchId());
                entityXfGoodsListProcess.setPId(request.getPId());
                entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
                entityXfGoodsListProcess.setReceiptId(0);
                entityXfGoodsListProcess.setConsTime(entityXfRecordProcess.getConsTime());
                entityXfGoodsListProcess.setMealDate(entityXfShoppingCart.getMealDate());
                entityXfGoodsListProcess.setMealNo(entityXfShoppingCart.getMealNo());
                entityXfGoodsListProcess.setConsType(entityXfRecordProcess.getConsType());
                entityXfGoodsListProcess.setDishesId(entityXfShoppingCart.getDishesId());
                entityXfGoodsListProcess.setDishesName(entityXfShoppingCart.getDishesName());
                entityXfGoodsListProcess.setPriceMode(entityXfShoppingCart.getPriceMode());
                entityXfGoodsListProcess.setWeightNumber(entityXfShoppingCart.getWeightNumber());
                entityXfGoodsListProcess.setDishesPrice(entityXfShoppingCart.getDishesPrice());
                entityXfGoodsListProcess.setUnitPrice(0);
                entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());

                if (exist.contains(key)) {
                    for (ShoppingCartRecordVo shoppingCartRecordVo : recordVoList) {
                        if (shoppingCartRecordVo.getMealDate().equals(entityXfShoppingCart.getMealDate())
                                && shoppingCartRecordVo.getMealNo().equals(entityXfShoppingCart.getMealNo().toString())
                                && shoppingCartRecordVo.getPointId().equals(entityXfShoppingCart.getPointId().longValue())
                        ) {
                            shoppingCartRecordVo.setConsMoney(shoppingCartRecordVo.getConsMoney() - Math.abs(entityXfShoppingCart.getDishesPrice()));
                            shoppingCartRecordVo.setRealMoney(shoppingCartRecordVo.getConsMoney());
                            entityXfGoodsListProcess.setOrderNo(shoppingCartRecordVo.getOrderNo());
                            shoppingCartRecordVo.getGoodList().add(entityXfGoodsListProcess);
                            break;
                        }
                    }

                } else {
                    exist.add(key);
                    inx++;
                    ShoppingCartRecordVo shoppingCartRecordVo1 = (ShoppingCartRecordVo) DeepCopyUtil.deepCopy(entityXfRecordProcess);
                    shoppingCartRecordVo1.setOrderNo(shoppingCartRecordVo1.getOrderNo()+String.format("%03d", inx));
                    shoppingCartRecordVo1.setConsMoney(-1l * Math.abs(entityXfShoppingCart.getDishesPrice()));
                    shoppingCartRecordVo1.setRealMoney(shoppingCartRecordVo1.getConsMoney());
                    shoppingCartRecordVo1.setMealDate(entityXfShoppingCart.getMealDate());
                    shoppingCartRecordVo1.setMealNo(entityXfShoppingCart.getMealNo().toString());
                    shoppingCartRecordVo1.setPointId(entityXfShoppingCart.getPointId().longValue());
                    entityXfGoodsListProcess.setOrderNo(shoppingCartRecordVo1.getOrderNo());
                    shoppingCartRecordVo1.getGoodList().add(entityXfGoodsListProcess);
                    recordVoList.add(shoppingCartRecordVo1);
                }
            }
            exist = null;

            //插入订单


//            -----------------------------------------------一、计算优惠开始------------------------------------


            //1.判断账户类型是否有优惠设置
            int exDiscount = xfDiscountConfigServcie.existDiscount(request.getCompanyId(),null,entityXfAccountInfo.getAccTypeId(),1,null);

            log.info("查询是否有优惠规则 7ffYhPLb 【{}】【{}】【{}】整理后数据【{}】",request.getCompanyId(),request,exDiscount,recordVoList);


            if(exDiscount>0){

                String beginDate = DateUtil.getStrDate(recordVoList.get(0).getMealDate(),"yyyy-MM")+"-01";
                String endDate = DateUtils.getendDate(recordVoList.get(recordVoList.size()-1).getMealDate(),"yyyy-MM-dd");

                UserOrdersQueryVo queryVo =new UserOrdersQueryVo();
                queryVo.setConsType(1);
                queryVo.setComId(request.getCompanyId());
                queryVo.setPId(request.getPId());
                queryVo.setStartDate(beginDate);
                queryVo.setEndDate(endDate);

                List<EntityXfRecordProcessExxx> processExxxList = xfRecordProcessExxxService.getUserOrders(request.getCompanyId(),queryVo);


                for (ShoppingCartRecordVo shoppingCartRecordVo:recordVoList){
                    int discount = xfDiscountConfigServcie.selectSiscountBatch(request.getCompanyId(),shoppingCartRecordVo,processExxxList);
                    
                    long realMoney = shoppingCartRecordVo.getConsMoney() + discount;
                    shoppingCartRecordVo.setDiscount(Long.valueOf(discount));
                    shoppingCartRecordVo.setRealMoney(realMoney);
                    shoppingCartRecordVo.setPayAmount(Long.valueOf(Math.abs(realMoney)));

                    EntityXfRecordProcess entityXfRecordProcess1 = (EntityXfRecordProcess)shoppingCartRecordVo;
                    String stro = JsonUtils.toJson(entityXfRecordProcess1);
                    processExxxList.add(JsonUtils.fromJson(stro,EntityXfRecordProcessExxx.class));

                }

            }

            log.info("计算优惠后数据 53ejuXHD 【{}】【{}】【{}】",request.getCompanyId(),request,recordVoList);



//            -----------------------------------------------一、计算优惠结束------------------------------------


            //二、计算限制


            boolean ef = xfRecordProcessService.saveShoppingCard(request.getCompanyId(), recordVoList);

            if (!ef) {

                xfShoppingCartService.updateDishesFormCart(request.getCompanyId(),request,0);

                return ResultUtil.error(ResultEnum.Err_6004);
            }



//            if(true){
//                //测试
//                return ResultUtil.success();
//            }


            //支付金额
            long payAmount = recordVoList.stream().mapToLong(ShoppingCartRecordVo::getRealMoney).sum();
            entityXfRecordProcess.setConsMoney(payAmount);
            entityXfRecordProcess.setRealMoney(payAmount);


            HashMap<Object, Object> map = new HashMap<>();
            map.put("totalFee", Math.abs(payAmount));

            if (request.getType() == 9) {
                if(true){
                    return ResultUtil.error(ResultEnum.Err_3073);
                }

                //TODO 代扣影响大 后续再处理！！！！！！！！！！！！！！！！！！

                QrCardPayRequest qrCardPayRequest = new QrCardPayRequest();
                qrCardPayRequest.setCompanyId(request.getCompanyId());
                qrCardPayRequest.setMachNo(entityXfRecordProcess.getDeviceNo());
                qrCardPayRequest.setTradeNo(entityXfRecordProcess.getPlatOrderNo());
                qrCardPayRequest.setAmount(entityXfRecordProcess.getRealMoney().intValue());
                qrCardPayRequest.setConsType(entityXfRecordProcess.getConsType());
                qrCardPayRequest.setConsState(entityXfRecordProcess.getConsState());
                qrCardPayRequest.setType(1);

                JSONObject jsonObject = new JSONObject();
                int payState = payFunService.withholding(entityXfRecordProcess, qrCardPayRequest, null, jsonObject, 4);

                if (payState == 2) {
                    xfShoppingCartService.updateDishesFormCart(request.getCompanyId(),request,0);
                    //支付失败
                    return ResultUtil.info(4024, jsonObject.getString("msg"));
                }

                if (payState == 1) {
                    map.put("type", 9);
                    map.put("result", "success");
                    map.put("message", "支付成功");
                    return ResultUtil.success(map);
                } else if (payState == -1) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                } else if (payState == -2) {
                    //代扣未签约"
                    return ResultUtil.error(ResultEnum.Err_3047);
                } else if (payState == -11) {
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                } else if (payState == -12) {
                    //余额不足
                    return ResultUtil.error(ResultEnum.Err_4024);
                } else {
                    //支付结果未知
                    return ResultUtil.error(ResultEnum.Err_3029);
                }

            } else if (request.getType() == 7) {
                //钱包
                try {
                    entityXfRecordProcess.setChargeMoney(payAmount);
                    entityXfRecordProcess.setSubMoney(0l);

                    Boolean bo = xfRecordProcessService.saveLxOrder3(entityXfRecordProcess.getComId(), entityXfRecordProcess, 0, 0);
                    if (!bo) {
                        xfShoppingCartService.updateDishesFormCart(request.getCompanyId(),request,0);
                        return ResultUtil.error(ResultEnum.Err_5000);
                    }

//                    Boolean aBoolean = xfGoodsListProcessService.saveXfGoodsListRecode(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());

                    //新增成功表的退款数据
//                    Date payTime = new Date();
//                    entityXfRecordProcess.setPayTime(payTime);
//                    entityXfRecordProcess.setPayState(1);

//                    Result sveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//                    log.info("迁移订餐结果到成功表ol5uOfxu 【{}】【{}】", entityXfRecordProcess.getOrderNo(), 123);

                    map.put("type", 5);
                    map.put("result", "success");
                } catch (Exception e) {
                    log.info("订餐异常lVzk7Glg 【{}】【{}】", request ,e);
                    return ResultUtil.error(ResultEnum.Err_3030);
                }

                try {
                    log.info("开始打印订单zMQGW2CL 订单：【{}】", entityXfRecordProcess);
                    PlanKitchenPrinterRequest planKitchenPrinterRequest = new PlanKitchenPrinterRequest();
                    planKitchenPrinterRequest.setComId(entityXfRecordProcess.getComId());
                    planKitchenPrinterRequest.setPointId(entityXfRecordProcess.getPointId());
                    planKitchenPrinterRequest.setOrderNo(entityXfRecordProcess.getOrderNo());
                    planKitchenPrinterRequest.setCheckPrint(true);

                    log.info("开始打印订单0KYSdk2W planKitchenPrinter：【{}】", planKitchenPrinterRequest);
                    Result printResult = payConfigClientService.planKitchenPrinter(planKitchenPrinterRequest);
                    log.info("订单打印结果2jxGMljy【{}】", printResult);
                } catch (Exception e) {
                    //e.printStackTrace();
                    log.info("订单打印异常PC2Tn0bV 【{}】【{}】", entityXfRecordProcess, e);
                }

                try {
                    for (ShoppingCartRecordVo shoppingCartRecordVo:recordVoList){
                        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                        mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                        mqSaveOrderVo.setId(shoppingCartRecordVo.getId());
                        mqSaveOrderVo.setMachNo(shoppingCartRecordVo.getDeviceNo());
                        saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式 YhTC7EUr:【{}】,机器号:【{}】定时任务-入库成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（定时任务处理）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }

                return ResultUtil.success(map);
            } else {

                //if opTypeDiff  == 201
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                String RealUrl = payUrl + "/unifiedpreorder/lordesau.do";

                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());

                stringObjectMap.put("pos_no", "0000000");
                stringObjectMap.put("devsnip", "127.0.0.1");
                stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                stringObjectMap.put("subject", "公众号批量订餐");
                stringObjectMap.put("total_amount", Math.abs(payAmount));
                stringObjectMap.put("fee_type", "CNY");
                stringObjectMap.put("trade_type", "JSAPI");
                stringObjectMap.put("payway", 3);
                stringObjectMap.put("body", request.getCompanyId().toString());
                stringObjectMap.put("operator", "admin");
                stringObjectMap.put("openid", request.getOpenId());

                //type  1微信官方  3 随行付微信  2建行
                if (request.getType() == 2) {
                    stringObjectMap.put("trade_type", "MWEB");
                    stringObjectMap.put("pay_way", 15);
                    stringObjectMap.put("payway", 15);
                }

                RequestUtil requestUtil = new RequestUtil();

                log.info("地址sZfA2LKh【{}】  参数【{}】", RealUrl, stringObjectMap);

                Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                Gson gson = new Gson();
                Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                log.info("公众号返回CMpv1mNV【{}】  ", result3);

                if (result3 == null || result3.getCode() != 200) {
                    return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));

                GzhParamVo gzhParamVo = GzhParamFormat.formate(jsonObject, request.getType());
                log.info("公众号参数VM2rp6bg【{}】 【{}】【{}】", request, entityXfRecordProcess.getPlatOrderNo(), gzhParamVo);
                return ResultUtil.success(gzhParamVo);
            }


        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式hWk6nIOK:【{}】,机器号:【{}】,请求参数:【{}】,异常2:【{}】,行号:【{}】", "支付请求（强在线）", request.getTradeNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


}
